// components/send-code/send-code.js
import { validatePhone } from '../../utils/util'

Component({
    properties: {
        validateCode: {
            type: String,
            value: ''
        },
        phone: {
            type: String,
            value: ''
        },
        border: {
            type: Boolean,
            value: true
        },
        time: {
            type: Number,
            value: 60
        }
    },
    data: {
        countdown: 0, // 倒计时
        loading: false // 是否正在发送验证码
    },
    methods: {
        /**
         * 获取验证码
         */
        getCode() {
            const { phone } = this.properties
            if (!validatePhone(phone)) {
                return wx.showToast({
                    title: '请输入正确的手机号',
                    icon: 'none'
                })
            }

            this.setData({ loading: true })

            this.triggerEvent('click', {
                success: this.successSend.bind(this),
                fail: this.failSend.bind(this)
            })
        },
        /**
         * 输入框改变时触发
         */
        onChange(e) {
            this.triggerEvent('change', e.detail)
        },
        /**
         * 验证码发送成功 开启倒计时
         */
        successSend() {
            wx.showToast({
                title: '短信已发送，请注意查收',
                icon: 'none'
            })
            this.setData({
                countdown: this.properties.time,
                loading: false
            })
            let timer = setInterval(() => {
                this.setData({
                    countdown: this.data.countdown - 1
                })
                if (this.data.countdown === 0) {
                    clearInterval(timer)
                }
            }, 1000)
        },
        /**
         * 验证码发送失败
         */
        failSend(msg) {
            this.setData({ loading: false })
            wx.showToast({
                title: msg || '发送失败，请稍后再试',
                icon: 'none'
            })
        }
    }
})
